package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.config.AppConfig;
import com.example.forum.dao.UserMapper;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/upload")
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class UploadController {

    // 上传根目录
    @Value("${spring.servlet.multipart.location:${java.io.tmpdir}}")
    private String tempUploadLocation;
    
    // 上传目录，相对于项目根目录
    private static final String UPLOAD_DIR = "upload";
    
    private String baseUploadPath;
    
    @PostConstruct
    public void init() {
        // 初始化上传基础目录，确保目录存在
        String projectRoot = System.getProperty("user.dir");
        baseUploadPath = projectRoot + File.separator + UPLOAD_DIR;
        log.info("上传基础目录: {}", baseUploadPath);
        
        // 确保基础目录存在
        Path basePath = Paths.get(baseUploadPath);
        try {
            if (!Files.exists(basePath)) {
                Files.createDirectories(basePath);
                log.info("创建基础上传目录成功: {}", basePath);
            }
            
            // 确保images和avatars子目录存在
            Path imagesPath = Paths.get(baseUploadPath, "images");
            if (!Files.exists(imagesPath)) {
                Files.createDirectories(imagesPath);
                log.info("创建图片上传目录成功: {}", imagesPath);
            }
            
            Path avatarsPath = Paths.get(baseUploadPath, "avatars");
            if (!Files.exists(avatarsPath)) {
                Files.createDirectories(avatarsPath);
                log.info("创建头像上传目录成功: {}", avatarsPath);
            }
        } catch (IOException e) {
            log.error("创建上传目录失败: {}", e.getMessage(), e);
        }
    }

    @PostMapping("/image")
    public AppResult<String> uploadImage(@RequestParam("file") MultipartFile file, 
                                        @RequestParam(value = "token", required = false) String token,
                                        HttpServletRequest request) {
        log.info("开始处理图片上传请求");
        log.info("请求源地址: {}", request.getRemoteAddr());
        log.info("请求头信息: Host={}, Referer={}, User-Agent={}", 
                request.getHeader("Host"), 
                request.getHeader("Referer"), 
                request.getHeader("User-Agent"));
        
        // 检查是否通过token参数验证
        User user = null;
        if (token != null && !token.isEmpty()) {
            log.info("从URL参数中获取到token: {}", token);
            // 这里简单处理，实际应该使用UserService处理token验证
            if (token.startsWith("用户已登录-")) {
                String username = token.split("-")[1];
                // 从UserService中获取用户信息，这里简化处理
                log.info("从token中提取的用户名: {}", username);
                // 将用户信息设置到session中
                HttpSession session = request.getSession(true);
                if (session.getAttribute(AppConfig.USER_SESSION) == null) {
                    // 模拟放入一个用户对象
                    user = new User();
                    user.setUsername(username);
                    session.setAttribute(AppConfig.USER_SESSION, user);
                    log.info("已将用户信息设置到session中: {}", username);
                } else {
                    user = (User) session.getAttribute(AppConfig.USER_SESSION);
                    log.info("session中已存在用户: {}", user.getUsername());
                }
            }
        }
        
        // 检查用户是否登录
        HttpSession session = request.getSession(false);
        if ((session == null || session.getAttribute(AppConfig.USER_SESSION) == null) && user == null) {
            log.warn("未登录用户尝试上传图片");
            return AppResult.failed("未登录，无法上传图片");
        }
        
        // 检查文件是否为空
        if (file == null || file.isEmpty()) {
            log.warn("上传的文件为空");
            return AppResult.failed("上传失败，文件为空");
        }
        
        // 检查文件类型
        String contentType = file.getContentType();
        log.info("文件内容类型: {}", contentType);
        if (contentType == null || !contentType.startsWith("image/")) {
            log.warn("上传的文件类型不是图片: {}", contentType);
            return AppResult.failed("上传失败，只支持图片文件");
        }
        
        try {
            // 创建年月日目录
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String datePath = sdf.format(new Date());
            
            // 使用Path API来创建目录，更可靠
            Path uploadDirPath = Paths.get(baseUploadPath, datePath);
            log.info("当前上传目录: {}", uploadDirPath.toString());
            
            if (!Files.exists(uploadDirPath)) {
                try {
                    Files.createDirectories(uploadDirPath);
                    log.info("创建目录成功: {}", uploadDirPath);
                } catch (IOException e) {
                    log.error("创建目录失败: {}", e.getMessage(), e);
                    
                    // 尝试使用系统临时目录
                    log.info("尝试使用系统临时目录: {}", tempUploadLocation);
                    uploadDirPath = Paths.get(tempUploadLocation, "upload", "images", datePath);
                    Files.createDirectories(uploadDirPath);
                    log.info("使用临时目录创建成功: {}", uploadDirPath);
                }
            }
            
            // 检查目录是否可写
            if (!Files.isWritable(uploadDirPath)) {
                log.error("目录不可写: {}", uploadDirPath);
                return AppResult.failed("上传失败，目录不可写");
            }
            
            // 获取原始文件名和扩展名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                originalFilename = "image.jpg";
            }
            log.info("原始文件名: {}", originalFilename);
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            
            // 生成新的文件名
            String newFilename = UUID.randomUUID().toString().replace("-", "") + extension;
            log.info("新文件名: {}", newFilename);
            
            // 构建文件完整路径
            Path destPath = uploadDirPath.resolve(newFilename);
            log.info("文件保存路径: {}", destPath);
            
            // 保存文件 - 先将文件写入到临时文件，然后移动到目标位置
            Path tempFile = Files.createTempFile("upload_", extension);
            file.transferTo(tempFile.toFile());
            Files.move(tempFile, destPath);
            log.info("文件保存成功，大小: {} 字节", Files.size(destPath));
            
            // 检查文件是否真的存在
            if (!Files.exists(destPath)) {
                log.error("文件保存后检查失败，文件不存在: {}", destPath);
                return AppResult.failed("上传失败，文件保存异常");
            }
            
            // 生成访问URL - 保持URL格式的一致性
            String fileUrl = "/upload/" + datePath + "/" + newFilename;
            log.info("文件上传成功，访问URL: {}", fileUrl);
            log.info("完整访问路径: {}", request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + fileUrl);
            
            // 检查文件权限
            log.info("文件权限: 可读={}, 可写={}, 可执行={}", 
                    Files.isReadable(destPath),
                    Files.isWritable(destPath),
                    Files.isExecutable(destPath));
            
            // 为了确保开发环境中也能访问上传的图片，将图片也复制到静态资源目录
            try {
                // 静态资源目录下的路径
                String staticDirPath = System.getProperty("user.dir") + File.separator + 
                                       "src" + File.separator + "main" + File.separator + 
                                       "resources" + File.separator + "static" + File.separator + 
                                       "upload" + File.separator + "images" + File.separator + datePath;
                
                // 确保目录存在
                Path staticDir = Paths.get(staticDirPath);
                if (!Files.exists(staticDir)) {
                    Files.createDirectories(staticDir);
                    log.info("创建静态资源目录: {}", staticDir);
                }
                
                // 复制文件到静态资源目录
                Path staticFilePath = staticDir.resolve(newFilename);
                Files.copy(destPath, staticFilePath, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
                log.info("文件已复制到静态资源目录: {}", staticFilePath);
            } catch (Exception e) {
                // 这里只记录日志，不影响主流程
                log.warn("复制到静态资源目录失败: {}", e.getMessage(), e);
            }
            
            return AppResult.success(fileUrl);
        } catch (IOException e) {
            log.error("文件上传失败: {}", e.getMessage(), e);
            return AppResult.failed("上传失败: " + e.getMessage());
        }
    }
    
    // 添加一个测试端点，用于检查图片是否可访问
    @GetMapping("/check/{date}/{filename}")
    public AppResult<String> checkImageExists(@PathVariable("date") String date, 
                                              @PathVariable("filename") String filename) {
        Path imagePath = Paths.get(baseUploadPath, date, filename);
        log.info("检查图片是否存在: {}", imagePath);
        
        if (Files.exists(imagePath)) {
            log.info("图片存在，大小: {} 字节", imagePath);
            return AppResult.success("图片存在，可以访问");
        } else {
            log.info("图片不存在: {}", imagePath);
            return AppResult.failed("图片不存在");
        }
    }
    
    // 添加一个直接获取图片的端点
    @GetMapping("/file/{date}/{filename}")
    public void getImageFile(@PathVariable("date") String date,
                              @PathVariable("filename") String filename,
                              HttpServletResponse response) {
        Path imagePath = Paths.get(baseUploadPath, date, filename);
        log.info("请求访问图片: {}", imagePath);
        
        if (!Files.exists(imagePath)) {
            log.warn("请求的图片不存在: {}", imagePath);
            try {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "Image not found");
            } catch (IOException e) {
                log.error("发送404响应失败", e);
            }
            return;
        }
        
        // 设置正确的MIME类型
        String contentType = getContentTypeFromFileName(filename);
        response.setContentType(contentType);
        response.setHeader("Cache-Control", "max-age=86400"); // 缓存24小时
        
        try {
            // 使用Files.copy直接复制文件到响应输出流
            Files.copy(imagePath, response.getOutputStream());
            response.getOutputStream().flush();
            log.info("图片返回成功: {}", imagePath);
        } catch (IOException e) {
            log.error("返回图片时发生错误: {}", e.getMessage(), e);
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error sending image");
            } catch (IOException ex) {
                log.error("发送错误响应失败", ex);
            }
        }
    }
    
    /**
     * 根据文件名获取内容类型
     * @param filename 文件名
     * @return 内容类型
     */
    private String getContentTypeFromFileName(String filename) {
        String extension = filename.substring(filename.lastIndexOf('.') + 1).toLowerCase();
        switch (extension) {
            case "jpg":
            case "jpeg":
                return "image/jpeg";
            case "png":
                return "image/png";
            case "gif":
                return "image/gif";
            case "webp":
                return "image/webp";
            default:
                return "application/octet-stream";
        }
    }

    // 添加头像上传专用端点
    @PostMapping("/avatar")
    public AppResult<String> uploadAvatar(@RequestParam("file") MultipartFile file, 
                                         @RequestParam(value = "token", required = false) String token,
                                         HttpServletRequest request) {
        log.info("开始处理头像上传请求");
        
        // 检查是否通过token参数验证
        User user = null;
        if (token != null && !token.isEmpty()) {
            log.info("从URL参数中获取到token: {}", token);
            // 这里简单处理，实际应该使用UserService处理token验证
            if (token.startsWith("用户已登录-")) {
                String username = token.split("-")[1];
                // 从UserService中获取用户信息，这里简化处理
                log.info("从token中提取的用户名: {}", username);
                // 将用户信息设置到session中
                HttpSession session = request.getSession(true);
                if (session.getAttribute(AppConfig.USER_SESSION) == null) {
                    // 模拟放入一个用户对象
                    user = new User();
                    user.setUsername(username);
                    session.setAttribute(AppConfig.USER_SESSION, user);
                    log.info("已将用户信息设置到session中: {}", username);
                } else {
                    user = (User) session.getAttribute(AppConfig.USER_SESSION);
                    log.info("session中已存在用户: {}", user.getUsername());
                }
            }
        }
        
        // 检查用户是否登录
        HttpSession session = request.getSession(false);
        if ((session == null || session.getAttribute(AppConfig.USER_SESSION) == null) && user == null) {
            log.warn("未登录用户尝试上传头像");
            return AppResult.failed("未登录，无法上传头像");
        }
        
        user = (User) session.getAttribute(AppConfig.USER_SESSION);
        log.info("用户 {} 正在上传头像", user.getUsername());
        
        // 检查文件是否为空
        if (file == null || file.isEmpty()) {
            log.warn("上传的头像文件为空");
            return AppResult.failed("上传失败，文件为空");
        }
        
        // 检查文件类型
        String contentType = file.getContentType();
        log.info("头像文件内容类型: {}", contentType);
        if (contentType == null || !contentType.startsWith("image/")) {
            log.warn("上传的头像文件类型不是图片: {}", contentType);
            return AppResult.failed("上传失败，只支持图片文件");
        }
        
        try {
            // 创建用户头像目录 - 使用固定的avatars目录
            String avatarDir = "avatars";
            
            // 使用Path API来创建目录
            Path uploadDirPath = Paths.get(baseUploadPath, avatarDir);
            log.info("头像上传目录: {}", uploadDirPath.toString());
            
            if (!Files.exists(uploadDirPath)) {
                try {
                    Files.createDirectories(uploadDirPath);
                    log.info("创建头像目录成功: {}", uploadDirPath);
                } catch (IOException e) {
                    log.error("创建头像目录失败: {}", e.getMessage(), e);
                    
                    // 尝试使用系统临时目录
                    uploadDirPath = Paths.get(tempUploadLocation, "upload", "avatars");
                    Files.createDirectories(uploadDirPath);
                    log.info("使用临时目录创建成功: {}", uploadDirPath);
                }
            }
            
            // 获取原始文件名和扩展名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                originalFilename = "avatar.jpg";
            }
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            
            // 生成新的文件名 - 使用用户ID作为前缀确保唯一性
            String newFilename = "user_" + user.getId() + "_" + 
                                 UUID.randomUUID().toString().substring(0, 8) + extension;
            log.info("新头像文件名: {}", newFilename);
            
            // 构建文件完整路径
            Path destPath = uploadDirPath.resolve(newFilename);
            log.info("头像保存路径: {}", destPath);
            
            // 保存文件
            file.transferTo(destPath.toFile());
            log.info("头像保存成功，大小: {} 字节", Files.size(destPath));
            
            // 生成访问URL - 保持URL格式的一致性
            String fileUrl = "/upload/avatars/" + newFilename;
            log.info("头像上传成功，访问URL: {}", fileUrl);
            
            // 为了确保开发环境中也能访问上传的头像，将图片也复制到静态资源目录
            try {
                // 静态资源目录下的路径
                String staticDirPath = System.getProperty("user.dir") + File.separator + 
                                       "src" + File.separator + "main" + File.separator + 
                                       "resources" + File.separator + "static" + File.separator + 
                                       "upload" + File.separator + "avatars";
                
                // 确保目录存在
                Path staticDir = Paths.get(staticDirPath);
                if (!Files.exists(staticDir)) {
                    Files.createDirectories(staticDir);
                    log.info("创建静态资源头像目录: {}", staticDir);
                }
                
                // 复制文件到静态资源目录
                Path staticFilePath = staticDir.resolve(newFilename);
                Files.copy(destPath, staticFilePath, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
                log.info("头像已复制到静态资源目录: {}", staticFilePath);
            } catch (Exception e) {
                // 这里只记录日志，不影响主流程
                log.warn("复制到静态资源目录失败: {}", e.getMessage(), e);
            }
            
            // 直接更新用户头像URL字段
            try {
                // 获取用户Mapper直接更新
                UserMapper userMapper = SpringContextUtil.getBean(UserMapper.class);
                if (userMapper != null) {
                    // 创建只包含头像URL的用户对象
                    User updateUser = new User();
                    updateUser.setId(user.getId());
                    updateUser.setAvatarUrl(fileUrl);
                    
                    // 直接更新数据库
                    int result = userMapper.updateByPrimaryKeySelective(updateUser);
                    
                    if (result == 1) {
                        // 更新成功，同时更新session中的用户信息
                        user.setAvatarUrl(fileUrl);
                        session.setAttribute(AppConfig.USER_SESSION, user);
                        log.info("用户 {} 的头像URL已更新: {}", user.getUsername(), fileUrl);
                    } else {
                        log.warn("更新用户头像URL失败，受影响行数={}", result);
                    }
                } else {
                    log.warn("无法获取UserMapper，头像URL未保存到用户资料");
                }
            } catch (Exception e) {
                log.error("更新用户头像URL失败: {}", e.getMessage(), e);
                // 不影响主流程，仍然返回成功
            }
            
            return AppResult.success(fileUrl);
        } catch (IOException e) {
            log.error("头像上传失败: {}", e.getMessage(), e);
            return AppResult.failed("上传失败: " + e.getMessage());
        }
    }

    // 添加一个通用的文件访问端点 - 可以访问任意目录下的文件
    @GetMapping("/{directory}/{filename}")
    public void getUploadedFile(@PathVariable("directory") String directory,
                              @PathVariable("filename") String filename,
                              HttpServletResponse response) {
        // 安全检查 - 只允许访问特定目录，添加日期格式的目录
        boolean isAllowedDirectory = directory.equals("avatars") || 
                                     directory.equals("images") || 
                                     directory.matches("\\d{8}"); // 匹配日期格式目录，如20250513
                                     
        if (!isAllowedDirectory) {
            log.warn("尝试访问不允许的目录: {}", directory);
            try {
                response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access denied");
            } catch (IOException e) {
                log.error("发送403响应失败", e);
            }
            return;
        }
        
        Path filePath = Paths.get(baseUploadPath, directory, filename);
        log.info("请求访问文件: {}", filePath);
        
        if (!Files.exists(filePath)) {
            log.warn("请求的文件不存在: {}", filePath);
            try {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
            } catch (IOException e) {
                log.error("发送404响应失败", e);
            }
            return;
        }
        
        // 设置内容类型
        String contentType = getContentTypeFromFileName(filename);
        response.setContentType(contentType);
        
        // 设置跨域访问允许
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET");
        
        // 设置缓存相关的响应头
        response.setHeader("Cache-Control", "public, max-age=86400"); // 缓存1天
        response.setHeader("Pragma", "public");
        
        try {
            Files.copy(filePath, response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            log.error("发送文件时出错: {}", filePath, e);
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error sending file");
            } catch (IOException ex) {
                log.error("发送500响应失败", ex);
            }
        }
    }

    // 添加一个能够处理带日期目录的图片访问端点
    @GetMapping("/images/{date}/{filename}")
    public void getImageWithDate(@PathVariable("date") String date,
                                @PathVariable("filename") String filename,
                                HttpServletResponse response) {
        // 修改路径，直接从日期目录查找
        Path imagePath = Paths.get(baseUploadPath, date, filename);
        log.info("请求访问带日期的图片: {}", imagePath);
        
        if (!Files.exists(imagePath)) {
            // 如果文件不存在，尝试在images子目录下查找（向后兼容）
            Path alternativePath = Paths.get(baseUploadPath, "images", date, filename);
            log.info("在主目录未找到图片，尝试images子目录: {}", alternativePath);
            
            if (Files.exists(alternativePath)) {
                imagePath = alternativePath;
                log.info("在images子目录找到图片: {}", imagePath);
            } else {
                log.warn("请求的图片不存在: {}", imagePath);
                try {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, "Image not found");
                } catch (IOException e) {
                    log.error("发送404响应失败", e);
                }
                return;
            }
        }
        
        // 设置正确的MIME类型
        String contentType = getContentTypeFromFileName(filename);
        response.setContentType(contentType);
        
        // 设置跨域访问允许
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET");
        
        response.setHeader("Cache-Control", "max-age=86400"); // 缓存24小时
        
        try {
            // 使用Files.copy直接复制文件到响应输出流
            Files.copy(imagePath, response.getOutputStream());
            response.getOutputStream().flush();
            log.info("图片返回成功: {}", imagePath);
        } catch (IOException e) {
            log.error("返回图片时发生错误: {}", e.getMessage(), e);
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error sending image");
            } catch (IOException ex) {
                log.error("发送错误响应失败", ex);
            }
        }
    }

    // 添加专门处理默认头像的端点
    @GetMapping("/default-avatar")
    public void getDefaultAvatar(HttpServletResponse response) {
        Path defaultAvatarPath = Paths.get(System.getProperty("user.dir"), 
                "src", "main", "resources", "static", "images", "default-avatar.png");
        log.info("请求访问默认头像: {}", defaultAvatarPath);
        
        if (!Files.exists(defaultAvatarPath)) {
            log.warn("默认头像文件不存在: {}", defaultAvatarPath);
            try {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "Default avatar not found");
            } catch (IOException e) {
                log.error("发送404响应失败", e);
            }
            return;
        }
        
        // 设置内容类型
        response.setContentType("image/png");
        
        // 设置缓存相关的响应头
        response.setHeader("Cache-Control", "public, max-age=86400"); // 缓存1天
        response.setHeader("Pragma", "public");
        
        try (InputStream in = Files.newInputStream(defaultAvatarPath)) {
            OutputStream out = response.getOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush();
        } catch (IOException e) {
            log.error("发送默认头像时出错", e);
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error sending default avatar");
            } catch (IOException ex) {
                log.error("发送500响应失败", ex);
            }
        }
    }

    /**
     * 添加一个图片直接访问端点（应急解决方案）
     */
    @GetMapping("/direct-image/{datePath}/{filename}")
    public void getImageDirectly(@PathVariable("datePath") String datePath,
                               @PathVariable("filename") String filename,
                               HttpServletResponse response) {
        log.info("直接访问图片: datePath={}, filename={}", datePath, filename);
        
        // 优先尝试在日期目录查找
        Path imagePath = Paths.get(baseUploadPath, datePath, filename);
        
        // 如果不存在，尝试在images子目录下查找
        if (!Files.exists(imagePath)) {
            imagePath = Paths.get(baseUploadPath, "images", datePath, filename);
            log.info("在主目录未找到图片，尝试images子目录: {}", imagePath);
        }
        
        // 如果仍然不存在，尝试在静态资源目录查找
        if (!Files.exists(imagePath)) {
            String staticPath = System.getProperty("user.dir") + File.separator + "src" + File.separator 
                              + "main" + File.separator + "resources" + File.separator + "static" 
                              + File.separator + "upload" + File.separator + "images" + File.separator + datePath;
            imagePath = Paths.get(staticPath, filename);
            log.info("在upload目录未找到图片，尝试静态资源目录: {}", imagePath);
        }
        
        // 最终检查
        if (!Files.exists(imagePath)) {
            log.error("图片不存在: {}", imagePath);
            try {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "Image not found");
            } catch (IOException e) {
                log.error("发送404响应失败", e);
            }
            return;
        }
        
        // 设置响应头
        String contentType = getContentTypeFromFileName(filename);
        response.setContentType(contentType);
        
        // 设置跨域访问允许
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET");
        
        response.setHeader("Cache-Control", "public, max-age=86400");
        
        // 输出图片
        try (InputStream in = Files.newInputStream(imagePath)) {
            byte[] buffer = new byte[4096];
            OutputStream out = response.getOutputStream();
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush();
        } catch (IOException e) {
            log.error("读取或发送图片失败: {}", e.getMessage(), e);
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error sending image");
            } catch (IOException ex) {
                log.error("发送错误响应失败", ex);
            }
        }
    }
} 